package test.user;

import test.dao.UserDao;
import test.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/user")
public class UserListServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");//获取id参数
        if (id != null && id.length() > 0) { // 判断id不为空
            String act = req.getParameter("act");// 获取act的参数 用户判断是修改还是删除
            if ("edit".equals(act)) {
                update(req, resp); //修改
                // 获取到要查询的id
//                User user = userDao.queryById( Integer.parseInt(id));
//                System.out.println(user);
//                req.setAttribute("user",user);
//                req.setAttribute("a","123");
            } else if ("del".equals(act)) {
                delete(id); // 删除
            }
        }
        List<User> users = userDao.queryAll();//获取到所有数据
        req.setAttribute("users", users);
        req.getRequestDispatcher("/WEB-INF/views/user.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        int count = userDao.update(
                name,Integer.parseInt(age),Integer.parseInt(id)
        );
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        if(count > 0){
            //
            out.println("修改成功");
        }else{
            out.println("修改失败");
        }
        out.println("<a href='?s=1'>继续</a>");

    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
        // 获取到要查询的id
        int id = Integer.parseInt(req.getParameter("id"));
        User user = userDao.queryById(id);
        System.out.println(user);
        req.setAttribute("user",user);
    }

    private void delete(String id) {
        int count = userDao.delete(Integer.parseInt(id));
        if (count == 0) {
            System.out.println("删除失败");
        } else {
            System.out.println("删除成功");
        }
    }
}
